import React, { useState } from "react";
import { Button } from "@/components/ui/button";
import { Loading } from "@/components/ui/loading";
import { useParams } from "react-router-dom";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { Input } from "@/components/ui/input";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import CustomUploader from "@/components/custom/uploader";
import { Modal } from "@/components/ui/modal";
import { useRequest } from "ahooks";

import {
  getHisMedicineDetail,
  // getCasbinConfig,
  // getCasbinPolicies,
} from "../../api";
import {
  UploadedFileI,
  HisMedicineI,
  RootStateI,
  RoleUserI,
} from "../../types";
import { useSelector } from "react-redux";
import request, { baseUrl } from "../../api/http_class";
import { hasPermission } from "@/lib/utils";
import { useToast } from "@/hooks/use-toast";

const MedicineDetail: React.FC = () => {
  const params = useParams();
  const { toast } = useToast();

  const user = useSelector((state: RootStateI) => state.user);
  const [medicine, setMedicine] = useState<HisMedicineI>();
  const [showUploadModal, setShowUploadModal] = useState<boolean>(false);

  const { run, loading } = useRequest(
    (id: string) => getHisMedicineDetail(id),
    {
      manual: false,
      defaultParams: [params.id ? params.id : ""],
      onSuccess(resp, params: any) {
        console.log(resp.data);
        setMedicine(resp.data);
      },
      onError(e: any, params: any) {
        toast({
          variant: "success",
          title: "数据获取成功",
          description: "",
          duration: 1600,
        });
      },
    }
  );

  const onDownload = (imgUrl: string) => {
    fetch(imgUrl)
      .then((response) => response.blob())
      .then((blob) => {
        const url = URL.createObjectURL(new Blob([blob]));
        const link = document.createElement<"a">("a");
        link.href = url;
        link.download = "image.png";
        document.body.appendChild(link);
        link.click();
        URL.revokeObjectURL(url);
        link.remove();
      });
  };

  const formSchema = z.object({
    id: z.string({ required_error: "请选择药品" }).min(3, {
      message: "药品id至少3位",
    }),
    serial: z.string({ required_error: "请选择药品" }).min(1, {
      message: "药品serial至少1位",
    }),
    specification: z.string({ required_error: "请选择药品" }).min(1, {
      message: "药品specification至少1位",
    }),
    drugname: z.string({ required_error: "请选择药品" }).min(3, {
      message: "药品id至少3位",
    }),
    files: z.array(z.instanceof(File)),
  });

  type FormValuesT = z.infer<typeof formSchema>;

  // 表单部分
  const form = useForm<FormValuesT>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      id: medicine?.id,
      serial: medicine?.serial,
      specification: medicine?.specification,
      drugname: medicine?.drugname,
      files: [],
    },
    mode: "onChange",
  });

  return (
    <div className="w-full">
      {medicine ? (
        <>
          <section>
            <h3 style={{ display: "inline" }}>{medicine.drugname}</h3>（
            {medicine.chargeCode}）
            {hasPermission(user, "update-his-medicine", "PUT") && (
              <Button
                className="size-8 px-6"
                onClick={() => {
                  form.setValue("id", medicine.id || "");
                  form.setValue("serial", medicine.serial || "");
                  form.setValue("specification", medicine.specification || "");
                  form.setValue("drugname", medicine.drugname || "");
                  form.setValue("files", []);
                  setShowUploadModal(true);
                }}
              >
                编辑
              </Button>
            )}
            <div className="grid grid-cols-4 gap-4 rounded-lg border p-4 hover:shadow-md">
              <Card>
                <CardHeader>包装规格</CardHeader>
                <CardContent>
                  <span>{medicine.specification}</span>
                </CardContent>
              </Card>
              <Card>
                <CardHeader>零售价</CardHeader>
                <CardContent>
                  <span>
                    {medicine.retailPrice
                      ? `￥${medicine.retailPrice.toFixed(2)}`
                      : ""}
                  </span>
                </CardContent>
              </Card>
              <Card>
                <CardHeader>生产厂商</CardHeader>
                <CardContent>
                  <span>{medicine.manufacture}</span>
                </CardContent>
              </Card>
              <Card>
                <CardHeader>说明书</CardHeader>
                <CardContent>
                  <a
                    href={
                      "http://10.2.3.199:9999/zlcx/data_detail.action?webHisId=" +
                      medicine.chargeCode +
                      medicine.serial +
                      "&hospitalCode=08110010"
                    }
                    target="_blank"
                    rel="noreferrer"
                  >
                    说明书
                  </a>
                </CardContent>
              </Card>
              <Card>
                <CardHeader>门诊费用类别</CardHeader>
                <CardContent>
                  <span>{medicine.mzChargeType}</span>
                </CardContent>
              </Card>
              <Card>
                <CardHeader>住院费用类别</CardHeader>
                <CardContent>
                  <span>{medicine.zyChargeType}</span>
                </CardContent>
              </Card>
            </div>
          </section>
          <section className="p-4 grid grid-cols-2 gap-4">
            {medicine.uploadedFiles?.map((item: UploadedFileI) => {
              return (
                <img
                  className="w-full h-auto transform transition-transform duration-300 hover:scale-150 hover:z-10"
                  key={item.id}
                  src={`${baseUrl}uploaded-files/${item.id}/`}
                  alt="img"
                />
              );
            })}
          </section>
        </>
      ) : (
        <div>
          <span>
            <Loading />
          </span>
        </div>
      )}
      <Modal
        title="上传图片"
        isOpen={showUploadModal}
        description="上传图片"
        onClose={() => setShowUploadModal(false)}
      >
        <Form {...form}>
          <FormField
            control={form.control}
            name="id"
            render={({ field }) => (
              <FormItem style={{ display: "none" }}>
                <FormLabel>药品ID</FormLabel>
                <FormControl>
                  <Input placeholder="id" {...field} disabled />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="serial"
            render={({ field }) => (
              <FormItem style={{ display: "none" }}>
                <FormLabel>包装规格</FormLabel>
                <FormControl>
                  <Input placeholder="serial" {...field} disabled />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="drugname"
            render={({ field }) => (
              <FormItem>
                <FormLabel>药品名称</FormLabel>
                <FormControl>
                  <Input placeholder="药品名称" {...field} disabled />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="specification"
            render={({ field }) => (
              <FormItem>
                <FormLabel>包装规格</FormLabel>
                <FormControl>
                  <Input placeholder="specification" {...field} disabled />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="files"
            render={({ field }) => (
              <FormItem>
                <FormLabel>相关图片</FormLabel>
                <FormControl>
                  <CustomUploader
                    data={[]}
                    onChange={(files: any) => {
                      console.log(files);
                      field.onChange(files);
                    }}
                    accept="image/*"
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <Button
            onClick={() => {
              // console.log(form.getValues());
              // console.log(form.getValues("files"));
              // console.log(form.getValues("id"));
              // console.log(form.getValues("serial"));
              // 使用formdata方式提交请求
              const formData = new FormData();
              formData.append("id", form.getValues("id"));
              formData.append("drugname", form.getValues("drugname"));
              formData.append("serial", form.getValues("serial"));
              form.getValues("files").forEach((file) => {
                formData.append("files", file);
              });
              console.log(formData);
              // 发送请求
              request({
                url: `/his-medicine/${form.getValues("id")}/form/`,
                method: "PUT",
                data: formData,
                headers: { "Content-Type": "multipart/form-data" },
              }).then(
                (res: any) => {
                  console.log(res);
                  toast({
                    variant: "success",
                    title: "图片上传成功",
                    description: "",
                  });
                  // 清空表单
                  form.reset();
                  // 关闭模态框
                  setShowUploadModal(false);
                  // 重新获取medicine数据
                  run(params.id ? params.id : "");
                },
                (err: any) => {
                  console.log(err);
                  toast({
                    variant: "destructive",
                    title: "数据导入失败",
                    description: "请检查网络或联系系统管理员",
                  });
                }
              );
            }}
          >
            提交
          </Button>
        </Form>
      </Modal>
    </div>
  );
};

export default MedicineDetail;
